package answercard;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

/**
 * 模板查找
 * @author chenkn
 * since 2018/12/20
 */
public class DynAnswerCard {

    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public static void main(String[] args) {
        Mat source  = Imgcodecs.imread("D:\\eclipse_wk\\opencv-master\\img\\a8.jpg");
        Mat template = Imgcodecs.imread("D:\\eclipse_wk\\opencv-master\\img\\template.jpg");
        process(source, template, 4);
    }


    /**
     * 模板匹配
     * @see  <a href="https://juejin.im/post/5a683cd06fb9a01cb316596d">预流</a>
     * @param source 源图像
     * @param template 模板图像
     * @param matchMethod:Imgproc.TM_SQDIFF=0;<br>标准平方差匹配：Imgproc.TM_SQDIFF_NORMED=1；
     *                   <br>相关性匹配：Imgproc.TM_CCORR=2；
     *                   <br>标准相关匹配：Imgproc.TM_CCORR_NORMED=3；
     *                   <br>相关性系数匹配：Imgproc.TM_CCOEFF=4；
     *                   <br>标准相关性系数匹配：Imgproc.TM_CCOEFF_NORMED=5
     */
    static void process(Mat source, Mat template, int matchMethod) {

//        int matchMethod = 5;

        Mat result = Mat.zeros(source.rows() - template.rows() + 1, source.cols() - template.cols() + 1, CvType.CV_32FC1);
        Imgproc.matchTemplate(source, template, result, matchMethod);
        Core.normalize(result, result, 0, 255, Core.NORM_MINMAX, -1, new Mat());
        //获得最可能点，MinMaxLocResult是其数据格式，包括了最大、最小点的位置x、y
        Core.MinMaxLocResult mlr = Core.minMaxLoc(result);
        System.out.println("相似值=================：最大：" + mlr.maxVal + "    最小：" + mlr.minVal);
        Point matchLoc = mlr.minLoc;
        if (matchMethod >= 2 && matchMethod <= 5) {
            matchLoc = mlr.maxLoc;
        }
        Point point = new Point(matchLoc.x + template.cols(), matchLoc.y + template.rows());
        //在原图上的对应模板可能位置画一个绿色矩形
        Imgproc.rectangle(source, matchLoc, point, new Scalar(0, 255, 0), 5);
        //将结果输出到对应位置
        Imgcodecs.imwrite("D://ask//temp.jpg", source);
    }

}
